#pragma once
#include "Socket.hpp"
#include <memory>
 #include <sys/wait.h>
using ioservice_t = std::function<void(std::shared_ptr<Socket> &sock, InetAddr &client)>;
class TcpServer
{
    public:
    TcpServer(uint16_t port, ioservice_t service) : _port(port),
                                                    _listensockptr(std::make_unique<TcpSocket>()),
                                                    _isrunning(false),
                                                    _service(service)
    {
        _listensockptr->BuildTcpSocketMethod(_port);
    }
    void Start()
    {
        // 建立链接
        _isrunning = true;
        while (_isrunning)
        {
            InetAddr client;
            int n = _listensockptr->AccpetSocketOrDie(&client);
            if (n < 0)
            {
                continue;
            }
            printf("accept success\n");
            pid_t id = fork();
            if (id < 0)
            {
                perror("fork fail\n");
                exit(FORK_FAIL);
            }
            else if (id == 0)
            {
                //子进程
                _listensockptr->Close();
                pid_t iid=fork();
                if(iid>0)
                exit(OK);
                else{
                 //执行任务
                 exit(OK);
                }


            }
            else
            {
                close(n);
                //等待
                pid_t rid=waitpid(id,nullptr,0);
                (void)rid;

            }
        }
        _isrunning=0;
    }

private:
    uint16_t _port;
    std::unique_ptr<Socket> _listensockptr;
    bool _isrunning;
      ioservice_t _service;
};